/*
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-14 00:59:54
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-14 18:27:23
 * @FilePath: /free-learning/src/utils/promise-upload.ts
 */
import { updateCourseChapters } from "@/api/course/course-chapters";
import { type CourseChapters } from "@/api/course/course-chapters/type";
import FileAPI from "@/api/file";
import { type UploadMessage, useUploadMessageStore } from "@/store";
export const VIDEO_TYPE = [
  "video/mp4",
  "video/avi",
  "video/mov",
  "video/wmv",
  "video/flv",
  "video/mpeg",
  "video/mpg",
  "video/m4v",
  "video/webm",
  "video/ogg",
  "video/ogv",
  "video/webm",
  "video/webm",
];
export interface File_Course_Chapters {
  file: File;
  courseChapters: CourseChapters;
  status: "waiting" | "uploading" | "error";
  message: UploadMessage;
}
class PromiseUpload {
  private file_course_chapters: File_Course_Chapters[];
  private uploadMessageStore = useUploadMessageStore();
  constructor() {
    this.file_course_chapters = [];
  }

  add(file: File, courseChapters: CourseChapters) {
    const message = this.uploadMessageStore.addUploadMessage(
      "资源上传",
      `${file.name}上传中，请稍后...`
    );
    ElNotification({
      title: "上传中",
      message: `${file.name}上传中，请稍后...`,
      type: "info",
    });
    this.file_course_chapters.push({ file, courseChapters, status: "waiting", message });
    this.upload();
  }

  upload() {
    this.file_course_chapters.forEach(async (item) => {
      // 如果文件状态为等待上传，则上传文件
      if (item.status === "waiting") {
        const res = await FileAPI.upload(item.file);
        item.status = "uploading";
        // 如果上传成功，则更新文件状态
        if (res.url) {
          item.courseChapters.chapterUrl = res.url;
          await updateCourseChapters(item.courseChapters);
          this.file_course_chapters.splice(this.file_course_chapters.indexOf(item), 1);
          this.uploadMessageStore.uploadSuccess(item.message.id);
          this.uploadMessageStore.updateUploadMessage(
            item.message.id,
            "上传成功",
            `文件 ${item.file.name} 上传成功`
          );
          ElNotification({
            title: "上传成功",
            message: `文件 ${item.file.name} 上传成功`,
            type: "success",
          });
        }
      }
    });
  }
}
export default PromiseUpload;
